# -*- coding: binary -*-

module Msf::Exploit::Remote::HTTP::Moodle::Version
  # Used to check if the version is correct: must contain at least one dot
  MOODLE_VERSION_PATTERN = '(\d+\.\d+(?:\.\d+)*)'

  # Extracts the Moodle version information from various sources
  #
  # @return [String,nil] moodle version if found, nil otherwise
  def moodle_version
    # detect version from /lib/upgrade.txt
    version = moodle_version_helper(normalize_uri(target_uri.path, 'lib', 'upgrade.txt'), /=== #{MOODLE_VERSION_PATTERN} ===/i)
    return version if version

    nil
  end

  def moodle_version_helper(url, regex)
    res = send_request_cgi!({
      'method' => 'GET',
      'uri' => url
    }, 3.5)
    if res
      match = res.body.match(regex)
      return match[1] if match
    end

    nil
  end
end
